package com.artron.mediaartron.ui.fragment.login;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.artron.baselib.base.BaseStaticFragment;
import com.artron.baselib.entity.Response;
import com.artron.baselib.utils.ToastUtil;
import com.artron.baselib.utils.UIUtils;
import com.artron.mediaartron.R;
import com.artron.mediaartron.data.config.Altar;
import com.artron.mediaartron.data.config.AppProfile;
import com.artron.mediaartron.data.entity.LoginData;
import com.artron.mediaartron.data.net.RetrofitHelper;
import com.artron.mediaartron.ui.activity.LoginActivity;
import com.artron.mediaartron.util.RegexUtils;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.Map;

import butterknife.BindView;
import rx.Observable;
import rx.functions.Action1;

/**
 * Class description here
 *
 * @author doing
 * @version 1.0.0
 * @since 2017-10-11.
 */

public class LoginFragment extends BaseStaticFragment implements View.OnClickListener {

    private static final String TAG = "LoginFragment";

    @BindView(R.id.LoginFragment_et_username)
    protected EditText mEtUsername;
    @BindView(R.id.LoginFragment_et_password)
    protected EditText mEtPassword;
    @BindView(R.id.LoginFragment_btn_login)
    protected Button mBtnLogin;
    @BindView(R.id.LoginFragment_tv_forget_psd)
    protected TextView mTvForgetPsd;
    @BindView(R.id.LoginFragment_iBtn_qq)
    protected ImageButton mIBtnQQ;
    @BindView(R.id.LoginFragment_iBtn_micro_blog)
    protected ImageButton mIBtnMicroBlog;
    @BindView(R.id.LoginFragment_iBtn_micro_weixin)
    protected ImageButton mIBtnWeiXin;
    @BindView(R.id.LoginFragment_rl_container)
    protected RelativeLayout mRlContainer;
    private UMShareAPI mUMShareAPI;

    public static LoginFragment newInstance() {
        Bundle args = new Bundle();
        LoginFragment fragment = new LoginFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    protected void initVariable() {
        mUMShareAPI = UMShareAPI.get(mContext);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_login;
    }

    @Override
    protected void initView() {
        mBtnLogin.setOnClickListener(this);
        mTvForgetPsd.setOnClickListener(this);
        mIBtnQQ.setOnClickListener(this);
        mIBtnMicroBlog.setOnClickListener(this);
        mRlContainer.setOnClickListener(this);
        mIBtnWeiXin.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.LoginFragment_btn_login:
                String mobile = mEtUsername.getText().toString();
                String password = mEtPassword.getText().toString();
                UIUtils.hiddenKeyboard(getView());

                if (!RegexUtils.isTelPhoneNum(mobile)) {
                    UIUtils.showSnackbar(getView(), "请输入正确手机号");
                    return;
                }

                if (TextUtils.isEmpty(password)) {
                    UIUtils.showSnackbar(getView(), "密码不能为空");
                    return;
                }

                Observable<Response<LoginData>> login = RetrofitHelper.getLoginApi().login(mobile, password);
                RetrofitHelper.subscript(login, new Action1<Response<LoginData>>() {
                    @Override
                    public void call(final Response<LoginData> response) {
                        if (response != null && "OK".equals(response.getStatus())) {
                            UIUtils.showSnackbar(getView(), "登录成功");
                            final FragmentActivity activity = getActivity();
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    Altar userInfo = AppProfile.getUserInfo();
                                    userInfo.login(response.getData());
                                    activity.setResult(LoginActivity.RESULT_OK);
                                    activity.finish();
                                }
                            }, 1000);
                        } else {
                            UIUtils.showSnackbar(getView(), "用户名或者密码错误");
                        }
                    }
                });
                break;

            case R.id.LoginFragment_tv_forget_psd:
                LoginActivity.start(mContext, LoginActivity.TYPE_RESET);
                break;
            case R.id.LoginFragment_iBtn_qq:
                mUMShareAPI.getPlatformInfo(getActivity(), SHARE_MEDIA.QQ, mUMAuthListener);
                break;
            case R.id.LoginFragment_iBtn_micro_weixin:
                mUMShareAPI.getPlatformInfo(getActivity(), SHARE_MEDIA.WEIXIN, mUMAuthListener);
                break;
            case R.id.LoginFragment_iBtn_micro_blog:
                mUMShareAPI.getPlatformInfo(getActivity(), SHARE_MEDIA.SINA, mUMAuthListener);
                break;
            case R.id.LoginFragment_rl_container:
                UIUtils.hiddenKeyboard(getView());
                break;
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_register:
                LoginActivity.start(mContext, LoginActivity.TYPE_REGISTER);
                break;

        }
        return super.onOptionsItemSelected(item);
    }

    UMAuthListener mUMAuthListener = new UMAuthListener() {


        @Override
        public void onStart(SHARE_MEDIA share_media) {
            Log.d(TAG, "onStart: ");

        }

        @Override
        public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
            if (map != null) {

                String platform;
                if ("WEIXIN".equals(share_media.toString())) {
                    platform = "wechat";
                } else if ("QQ".equals(share_media.toString())) {
                    platform = "qq";
                } else {
                    platform = "sina";
                }

                String uid = map.get("uid");
                String iconUrl = map.get("iconurl");
                Observable<Response<LoginData>> thirdLogin = RetrofitHelper.getLoginApi().thirdLogin(uid, platform, iconUrl);
                RetrofitHelper.subscript(thirdLogin, new Action1<Response<LoginData>>() {
                    @Override
                    public void call(final Response<LoginData> response) {
                        if (response != null && "OK".equals(response.getStatus())) {
                            UIUtils.showSnackbar(getView(), "登录成功");
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    Altar userInfo = AppProfile.getUserInfo();
                                    userInfo.login(response.getData());
                                    getActivity().setResult(LoginActivity.RESULT_OK);
                                    getActivity().finish();
                                    if (response.getData() != null &&
                                            TextUtils.isEmpty(response.getData().getMobile())) {
                                        LoginActivity.start(mContext, LoginActivity.TYPE_BIND_PHONE);
                                    }
                                }
                            }, 1000);
                        } else {
                            UIUtils.showSnackbar(getView(), "第三方登录错误");
                        }
                    }
                });

            }
        }

        @Override
        public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
            ToastUtil.show("第三方登录失败");
            Log.d(TAG, "onError: " + throwable);
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media, int i) {
            Log.d(TAG, "onCancel: ");
        }
    };


}
